package xin.marcher.module.comment.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xin.marcher.module.comment.domain.dto.SkuWaitCommentDTO;
import xin.marcher.module.comment.domain.entity.SkuCommentDO;
import xin.marcher.module.comment.repository.SkuCommentRepository;
import xin.marcher.module.common.constants.comment.CommentConstants;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对超过60天未评价的商品给出默认评价
 */
@Component
public class SysCommentJob {

    @Resource
    private SkuCommentRepository skuCommentRepository;

    @Scheduled(fixedDelay = 1000)
    public void start() {
        // 60天以外的，每次查询100条
        List<SkuWaitCommentDTO> skuWaitCommentDTOS = skuCommentRepository.listShouldSysComment(60, 100);
        if (CollectionUtils.isEmpty(skuWaitCommentDTOS)) {
            return;
        }

        // 生成系统默认评论
        List<SkuCommentDO> list = new ArrayList<>();
        for (SkuWaitCommentDTO dto : skuWaitCommentDTOS) {
            SkuCommentDO skuCommentDO = new SkuCommentDO();
            skuCommentDO.initCommon();
            skuCommentDO.setOrderNo(dto.getOrderNo());
            skuCommentDO.setSellerId(dto.getSellerId());
            skuCommentDO.setItemId(dto.getItemId());
            skuCommentDO.setSkuId(dto.getSkuId());
            skuCommentDO.setUserId(dto.getUserId());
            skuCommentDO.setSkuScore(CommentConstants.SOCRE_BEST);
            skuCommentDO.setSkuScoreComputed(skuCommentDO.getSkuScore() == CommentConstants.SCORE_ORDINARY ?
                    CommentConstants.SCORE_COMPUTED_ORDINARY : (skuCommentDO.getSkuScore() > CommentConstants.SCORE_ORDINARY ?
                    CommentConstants.SCORE_COMPUTED_GOOD : CommentConstants.SCORE_COMPUTED_BAD));
            skuCommentDO.setFirstText("系统默认评价");
            // 默认通过
            skuCommentDO.setFirstAuditStatus(CommentConstants.AUDIT_STATUS_PASS);
            skuCommentDO.setBaseTime(dto.getBaseTime());
            skuCommentDO.setSysCommentFlag(true);
            skuCommentDO.setFirstTime(new Date());
            list.add(skuCommentDO);
        }

        // 批量保存系统默认评论
        skuCommentRepository.batchSave(list);

        // 批量更新待评价为已完成
        List<Long> collect = skuWaitCommentDTOS.stream().map(SkuWaitCommentDTO::getId).collect(Collectors.toList());
        skuCommentRepository.finishWaitComment(collect);
    }

}
